import api from '../../../api/index';
import uploadOss from '../../../utils/uploadFileOss/index';
import dayjs from 'dayjs'
Page({
    /**
     * 页面的初始数据
     */
    data: {
        curDate: dayjs().format('YYYY-MM-DD'),
        curTempDate: new Date().getTime(),
        show: false,
        loading: false,
        formatter(type, value) {
            if (type === 'year') {
                return `${value}`;
            }
            if (type === 'month') {
                return `${value}`;
            }
            return value;
        },
		dateTime: '1',
        dataList: [],
        fileList1: [],
        fileList2: [],
        fileList3: [],
        foodImgList1: [],
        foodImgList2: [],
        foodImgList3: [],
        foodImgList4: [],
        recommend: {},
        isavaible: true,
        name5: '',
        fileList5: [],
        imagesUrl5: []
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
    },
    onShow: function () {
			this.setData({
				recommend: wx.getStorageSync('recommend')
			})
			const dateString = wx.getStorageSync('dateString')

				if (dateString) {
					this.setData({
						curDate: dateString
					})
				} 
			const userInfo = wx.getStorageSync('userInfo')
			if(!userInfo.height || !userInfo.weight) {
				this.setData({
					isavaible: false
				})
				return
			} else {
				this.getlist();
        const date = new Date(this.data.curDate);
        const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        const dayOfWeek = daysOfWeek[date.getDay()];
        console.log(dayOfWeek);
        this.setData({
            dayOfWeek
        })
			}
    },
    // --------------------------------------开始------------------------------------------------------------------------------------------------------------------
    //文件选择
    afterRead5(event) {
    const { file, callback } = event.detail;
    console.log('33333', file);
    const videoDuration = file.duration;
		const type = file.type
    if (videoDuration > 50 && type === 'video') {
      // 视频时长超过50秒，进行相应处理
      console.log('视频超过50秒');
      wx.showToast({
        title: '上传失败,视频超过50秒！',
        icon: 'none',
        duration: 2000
      })
    } else {
      // 视频时长符合要求，继续上传
      console.log('视频时长符合要求');
			// 如果是图片
			if(type === 'image') {

			} else if (type === 'video') {
				// 如果是视频
			}
      // console.log(file);
      // var num = []
      // num.push(file.url)
      // num.push(file.thumb)
      // console.log(num); 
      // this.setData({
      //   imagesUrl: []
      // })
      // this.uploadDIY5(
      //   num,
      //   0,
      //   0,
      //   0,
      //   num.length,
      //   num
      // )
    }

  },
  /* 删除图片*/
  deleteImg5(e) {
      console.log(e);
      console.log(this.data.fileList5);
    let fileList = this.data.fileList5;
    fileList.splice(e.detail.index, 1);
    this.setData({ fileList5: fileList });
  },
  uploadDIY5(filePaths, successUp, failUp, i, length, param) {
    // 正在上传
    // debugger
    param.doing = true // this.data.prove.doing = true;
    let that = this
    // wx.showLoading({
    //     title: `上传${i}/${length}张图片中`,
    //     duration: 1000
    // })

    uploadOss(filePaths[i])
      .then((res) => {
        console.log(res);
        successUp++
        i++
        let imagesUrl5 = this.data.imagesUrl5
        imagesUrl5.push(res.url)
        this.setData({
          imagesUrl5
        })
        console.log(this.data.imagesUrl5);
        if (i === length) {
          console.log(i);
          console.log(length);
          // 全部上传成功
          console.log(param);
          if (successUp === length) {
            param.uploadSuccess = true
            console.log('图片上传成功进入回调')
            let img = {
              url: this.data.imagesUrl5[0],
              name: `视频${length-1}`,
            }
            let fileList5 = this.data.fileList5;
            fileList5.push(img);
            console.log(fileList5);
            let updatedDataImg =  [{
              "file": this.data.imagesUrl5[1]
            }]
            let updatedData = fileList5.map(item => {
              const { url, name, ...rest } = item;
              return { file: url, ...rest };
            });

            updatedData = JSON.stringify({ videos: updatedData, images: updatedDataImg })
            this.setData({ updatedData5: updatedData });
            console.log(updatedData);
            this.setData({ fileList5: fileList5 });
            // wx.hideLoading()
            // that.savetmp(param.imagesUrl[0])
          } else {
            // 图片上传部分失败
            param.doing = false
            wx.hideLoading()
            wx.showToast({
              title: '上传图片失败,请重新上传！',
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          // 递归调用uploadDIY函数
          that.uploadDIY5(
            filePaths,
            successUp,
            failUp,
            i,
            length,
            param
          )
        }
      })
      .catch((e) => {
        console.log('---图片上传失败 catch--- e', e)
        param.doing = false
        failUp++
        wx.hideLoading()
        wx.showToast({
          title: '图片上传失败，请重新上传！',
          icon: 'none',
          duration: 2000
        })
      })
  },
// ----------------------------结束----------------------------------------------------------------------------------------------------------------



    onInput(event) {
        this.setData({
            curTempDate: event.detail,
        });
    },
    onClose() {
    },
		goSetHW() {
			wx.navigateTo({
        url: `/pages/login/height?type=enterfood`,
      })
		},
    confirmDate() {
        const datea = this.data.curDate
        const dateb = dayjs(this.data.curTempDate).format('YYYY-MM-DD')
        const date = new Date(dateb);
        const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        const dayOfWeek = daysOfWeek[date.getDay()];
        console.log(dayOfWeek);
        this.setData({
            dayOfWeek
        })
        if (datea == dateb) {
            return
        }
        this.setData({
            curDate: dayjs(this.data.curTempDate).format('YYYY-MM-DD')
        })
        this.getlist()
    },

    selDate: function (evt) {
        this.setData({
            curTempDate: dayjs(this.data.curDate).valueOf(),
            show: true
        })
    },
    delFoods(e) {
        let id = e.currentTarget.dataset.id
        const _this = this
        wx.showModal({
            title: '',
            content: '确定要删除吗？',
            confirmColor: "#eb2444",
            success(res) {
                if (res.confirm) {
                    try {
                        wx.showLoading();
                        api.get(`/api/hxhealth/datetimefood/remove/${id}`).then((res) => {
                            wx.hideLoading()
                            _this.getlist()
                        });
                    } catch (e) {
                        console.error(e);
                    }
                }
            }
        })
    },
		addFood(e) {
			let time = e.currentTarget.dataset.time
			wx.navigateTo({
        url: `/dietaryRecommendations/pages/enterfoodlist/index?curDate=${this.data.curDate}&time=${time}`,
      })
		},
		delFoodImg(e) {
			let dateTime = e.currentTarget.dataset.datetime
			let index = e.currentTarget.dataset.index
			this.setData({
				dateTime: dateTime
			})
			if (dateTime == 1) {
				const list = []
				this.data.foodImgList1.forEach((item, index1) => {
					if (index !== index1) {
						list.push(item)
					}
				})
				this.setData({
					foodImgList1: list
				})
				this.saveFoodImg(this.data.foodImgList1)
			} else if (dateTime == 2) {
				const list = []
				this.data.foodImgList2.forEach((item, index1) => {
					if (index !== index1) {
						list.push(item)
					}
				})
				this.setData({
					foodImgList2: list
				})
				this.saveFoodImg(this.data.foodImgList2)
			} else if (dateTime == 3) {
				const list = []
				this.data.foodImgList3.forEach((item, index1) => {
					if (index !== index1) {
						list.push(item)
					}
				})
				this.setData({
					foodImgList3: list
				})
				this.saveFoodImg(this.data.foodImgList3)
			} else if (dateTime == 4) {
				const list = []
				this.data.foodImgList4.forEach((item, index1) => {
					if (index !== index1) {
						list.push(item)
					}
				})
				this.setData({
					foodImgList4: list
				})
				this.saveFoodImg(this.data.foodImgList4)
			}
		},
    addFoodImg(e) {
        console.log(e);
        let time = e.currentTarget.dataset.time
				this.setData({
					dateTime: time
				})
        if ((this.data.dateTime == 1 && this.data.foodImgList1.length === 5) || (this.data.dateTime == 2 && this.data.foodImgList2.length === 5) || 
				(this.data.dateTime == 3 && this.data.foodImgList3.length === 5) || (this.data.dateTime == 4 && this.data.foodImgList4.length === 5) ) {
					wx.showToast({
						title: '最多上传5个文件',
						icon: 'none',
						duration: 2000
					})
					return
				}
        // wx.chooseImage({
        //     count: 5, // 可选择的图片数量
        //     sizeType: ['compressed'], // 压缩图片
        //     sourceType: ['album', 'camera'], // 来源：相册或相机
        //     success:  (res)=> {
				// 			var num = []
				// 			res.tempFilePaths.forEach(file => {
				// 				num.push(file)
				// 			})
				// 			console.log(res,'res')

				// 			this.uploadDIY1(
				// 					num,
				// 					0,
				// 					0,
				// 					0,
				// 					num.length,
				// 					num
				// 			) 
        //     }
        //   })
				wx.chooseMedia({
            count: 5, // 可选择的图片数量
            mediaType: ['image','video'],
            sourceType: ['album', 'camera'],
						maxDuration: 50,
						camera: 'back',
            success:  (res)=> {
							console.log(res,'AAA')
							var num = []
							res.tempFiles.forEach(file => {
								num.push(file.tempFilePath)
							})

							this.uploadDIY1(
									num,
									0,
									0,
									0,
									num.length,
									num
							) 
            }
          })
    },
		uploadDIY(filePaths, successUp, failUp, i, length, param) {
			// 正在上传
			// debugger
			param.doing = true // this.data.prove.doing = true;
			param.imagesUrl = []
			let that = this
			// wx.showLoading({
			//     title: `上传${i}/${length}张图片中`,
			//     duration: 1000
			// })
			uploadOss(filePaths[i])
					.then((res) => {
							successUp++
							i++
							param.imagesUrl.push(res.url)
							if (i === length) {
									// 全部上传成功
									console.log('图片上传成功后的url', param.imagesUrl, length)
									if (successUp === length) {
											param.uploadSuccess = true
											console.log('图片上传成功进入回调')
											let img = {
												url: param.imagesUrl,
												name: '图片1',
										}
										let fileList = this.data.fileList;
											fileList.push(img);
											this.setData({fileList: fileList});
											// wx.hideLoading()
											// that.savetmp(param.imagesUrl[0])
									} else {
											// 图片上传部分失败
											param.doing = false
											wx.hideLoading()
											wx.showToast({
													title: '上传图片失败,请重新上传！',
													icon: 'none',
													duration: 2000
											})
									}
							} else {
									// 递归调用uploadDIY函数
									that.uploadDIY(
											filePaths,
											successUp,
											failUp,
											i,
											length,
											param
									)
							}
					})
					.catch((e) => {
							console.log('---图片上传失败 catch--- e', e)
							param.doing = false
							failUp++
							wx.hideLoading()
							wx.showToast({
									title: '图片上传失败，请重新上传！',
									icon: 'none',
									duration: 2000
							})
					})
		},
    getlist() {
			this.setData({
				foodImgList1: [],
				foodImgList2: [],
				foodImgList3: [],
				foodImgList4: []
			})
        api
            .post('/api/hxhealth/datetimefood/list2', {
                data: {
                    date: this.data.curDate
                }
            })
            .then((res) => {
                console.log(res);
                // [{"date":"2024-02-18","inputamount":"3.0","kcal":"48.000","inputunit":"个","foodimage":"https://hxhealth.oss-cn-beijing.aliyuncs.com/73865c85bbfc3d3954e7210c7237.jpg","sandamount":"30","id":"21373","time":"2","food":["2237","鹌鹑蛋"]},{"date":"2024-02-18","inputamount":"2.0","kcal":"32.000","inputunit":"个","foodimage":"https://hxhealth.oss-cn-beijing.aliyuncs.com/73865c85bbfc3d3954e7210c7237.jpg","sandamount":"20","id":"21362","time":"3","food":["2237","鹌鹑蛋"]}]
                if (res.length > 0) {
                    let data = res[0].foods
										let datas = res[0].datas
                    let sumTime1 = 0;
                    let sumTime2 = 0;
                    let sumTime3 = 0;
                    data.forEach(item => {
                        item.kcal = parseFloat(item.kcal).toFixed(1).replace(/\.0+$/, "")
                        if (item.time === "1") {
                            console.log(item.kcal);
                            sumTime1 += parseFloat(item.kcal);
                        } else if (item.time === "2") {
                            console.log(item.kcal)
                            sumTime2 += parseFloat(item.kcal);
                        } else if (item.time === "3") {
                            sumTime3 += parseFloat(item.kcal);
                        }
                    });
										datas.forEach(item => {
											const imgPath = []
											JSON.parse(item.data).images.forEach(item => {
												imgPath.push(item.file)
											})
											JSON.parse(item.data).videos.forEach(item => {
												imgPath.push(item.file)
											})
											if (item.time == '1') {
												this.setData({
													foodImgList1: imgPath
												})
												console.log(this.data.foodImgList1, 'ssssss')
											} else if (item.time == '2') {
												this.setData({
													foodImgList2: imgPath
												})
											} else if (item.time == '3') {
												this.setData({
													foodImgList3: imgPath
												})
											} else if (item.time == '4') {
												this.setData({
													foodImgList4: imgPath
												})
											}
										})

                    const target1 = Number(this.data.recommend.time1) - sumTime1;
                    const target2 = Number(this.data.recommend.time2) - sumTime2;
                    const target3 = Number(this.data.recommend.time3) - sumTime3;
                    this.setData({
                        dataList: data,
                        comparekcal1: target1,
                        comparekcal2: target2,
                        comparekcal3: target3,
                        'fileList1': data?.filter(row => row.time == 1) || [],
                        'fileList2': data?.filter(row => row.time == 2) || [],
                        'fileList3': data?.filter(row => row.time == 3) || [],
                        'fileList4': data?.filter(row => row.time == 4) || [],
                    });
                    //     res[i].kcal =  parseFloat(res[i].kcal).toFixed(1).replace(/\.0+$/, "")
                } else {
                    this.setData({
                        comparekcal1: 682,
                        comparekcal2: 910,
                        comparekcal3: 682,
                        'fileList1': [],
                        'fileList2': [],
                        'fileList3': [],
                        'fileList4': []
                    });
                }
                // console.log(JSON.stringify(res));
                
            })
            .catch((e) => {
                console.log('error', e);
            });
    },
    //文件选择-早餐
    afterRead(event) {
        const {
            file
        } = event.detail;
        console.log(file);
        var num = [];
        num.push(file.url);
        console.log(num);
        console.log(num);
        this.uploadDIY(num, 0, 0, 0, num.length, num, 'breakfast');
    },
    //文件选择-早餐
    afterRead1(event) {
        const {
            file
        } = event.detail;
        console.log(file);
        var num = [];
        num.push(file.url);
        console.log(num);
        console.log(num);
        this.uploadDIY(num, 0, 0, 0, num.length, num, 'lunch');
    },
    //文件选择-早餐
    afterRead2(event) {
        const {
            file
        } = event.detail;
        console.log(file);
        var num = [];
        num.push(file.url);
        console.log(num);
        console.log(num);
        this.uploadDIY(num, 0, 0, 0, num.length, num, 'dinner');
    },
    /* 删除图片-早餐*/
    deleteImg(e) {
        let fileList = this.data.fileList;
        fileList.splice(e.detail.index, 1);
        this.setData({
            fileList: fileList
        });
    },
    /* 删除图片-午餐*/
    deleteImg1(e) {
        let fileList = this.data.fileList1;
        fileList.splice(e.detail.index, 1);
        this.setData({
            fileList1: fileList
        });
    },
    /* 删除图片-晚餐*/
    deleteImg2(e) {
        let fileList = this.data.fileList2;
        fileList.splice(e.detail.index, 1);
        this.setData({
            fileList2: fileList
        });
    },
		bindPlayVideo(e) {
			console.log(e.target.dataset.item,'addd')
			wx.previewMedia({
				sources: [{
					url: e.target.dataset.item,
					type: 'video'
				}]
			})
		},
		saveFoodImg(data) {
			const post = {
				images: [],
				videos: []
			}
			const list = []
			data.forEach(item => {
				if (item.indexOf('.mp4') > -1 || item.indexOf('.avi') > -1) {
					post.videos.push({
						file: item
					})
				} else {
					post.images.push({
						file: item
					})
				}
			})
			api.post('/api/hxhealth/datetimefood/add', {
					data: {
						date: this.data.curDate,
						time: this.data.dateTime,
						data: JSON.stringify(post)
					}
			}).then(res => {
			}).catch(error => {
				wx.showToast({
					title: '图片保存失败',
					icon: 'none',
					duration: 2000
				})
			})
		},
    uploadDIY1(filePaths, successUp, failUp, i, length, param, name) {
			console.log(length, 'uploadDIY')
        // 正在上传
        // debugger
        param.doing = true; // this.data.prove.doing = true;
        param.imagesUrl = [];
        let that = this;
        // wx.showLoading({
        //     title: `上传${i}/${length}张图片中`,
        //     duration: 1000
        // })

        uploadOss(filePaths[i])
            .then((res) => {
                successUp++;
                i++;
                param.imagesUrl.push(res.url);
                if (i === length) {
                    // 全部上传成功
                    console.log('图片上传成功后的url1', param.imagesUrl[0], length);
                    if (successUp === length) {
											if (this.data.dateTime == 1) {
												let fileList = this.data.foodImgList1;
												if (this.data.foodImgList1.length === 5) {
													wx.showToast({
														title: '最多上传5张图片',
														icon: 'none',
														duration: 2000
													})
													return
												}
												fileList.push(param.imagesUrl[0]);
												this.setData({foodImgList1: fileList});
												this.saveFoodImg(this.data.foodImgList1)
											} else if (this.data.dateTime == 2) {
												let fileList = this.data.foodImgList2;
												if (this.data.foodImgList2.length === 5) {
													wx.showToast({
														title: '最多上传5张图片',
														icon: 'none',
														duration: 2000
													})
													return
												}
												fileList.push(param.imagesUrl[0]);
												this.setData({foodImgList2: fileList});
												this.saveFoodImg(this.data.foodImgList2)
											} else if (this.data.dateTime == 3) {
												let fileList = this.data.foodImgList3;
												if (this.data.foodImgList3.length === 5) {
													wx.showToast({
														title: '最多上传5张图片',
														icon: 'none',
														duration: 2000
													})
													return
												}
												fileList.push(param.imagesUrl[0]);
												this.setData({foodImgList3: fileList});
												this.saveFoodImg(this.data.foodImgList3)
											} else if (this.data.dateTime == 4) {
												let fileList = this.data.foodImgList4;
												if (this.data.foodImgList4.length === 5) {
													wx.showToast({
														title: '最多上传5张图片',
														icon: 'none',
														duration: 2000
													})
													return
												}
												fileList.push(param.imagesUrl[0]);
												this.setData({foodImgList4: fileList});
												this.saveFoodImg(this.data.foodImgList4)
											}
                    } else {
                        // 图片上传部分失败
                        param.doing = false;
                        wx.hideLoading();
                        wx.showToast({
                            title: '上传图片失败,请重新上传！',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                } else {
									console.log('图片上传成功后的url2', param.imagesUrl[0], length);
									if (this.data.dateTime == 1) {
										let fileList = this.data.foodImgList1;
										fileList.push(param.imagesUrl[0]);
										this.setData({foodImgList1: fileList});
									} else if (this.data.dateTime == 2) {
										let fileList = this.data.foodImgList2;
										fileList.push(param.imagesUrl[0]);
										this.setData({foodImgList2: fileList});
									} else if (this.data.dateTime == 3) {
										let fileList = this.data.foodImgList3;
										fileList.push(param.imagesUrl[0]);
										this.setData({foodImgList3: fileList});
									} else if (this.data.dateTime == 4) {
										let fileList = this.data.foodImgList4;
										fileList.push(param.imagesUrl[0]);
										this.setData({foodImgList4: fileList});
									}
                    // 递归调用uploadDIY函数
                    that.uploadDIY1(filePaths, successUp, failUp, i, length, param);
                }
            })
            .catch((e) => {
                console.log('---图片上传失败 catch--- e', e);
                param.doing = false;
                failUp++;
                wx.hideLoading();
                wx.showToast({
                    title: '图片上传失败，请重新上传！',
                    icon: 'none',
                    duration: 2000
                });
            });
    },

    formSubmit: function (e) {
        if (this.data.fileList.length == 0 && this.data.fileList1.length == 0 && this.data.fileList2.length == 0) {
            wx.showModal({
                title: '提示',
                content: '请上传菜品图片!'
            });
            return false;
        } else {
            this.setData({
                loading: true
            });
            console.log('====================================');
            console.log(this.data.fileList);
            console.log('====================================');

            let status = false;
            api
                .post('/api/hxhealth/datefood/save', {
                    data: {
                        date: '2023-11-16',
                        foods: this.data.fileList
                    }
                })
                .then((res) => {
                    wx.showToast({
                        title: '反馈成功'
                    });
                    //提示框消失后返回上一级页面
                    setTimeout(() => {
                        wx.navigateBack({
                            change: true
                        });
                    }, 1200);
                })
                .catch((e) => {
                    console.log(e);
                    wx.showToast({
                        icon: 'error',
                        duration: 1200,
                        title: '反馈失败：' + e.faultstring
                    });
                });
            return status;
        }
    },
    godietaryanalysis() {
        if (this.data.dataList.length > 0) {
            wx.navigateTo({ url: `/dietaryRecommendations/pages/dietaryanalysis/index?curDate=${this.data.curDate}` });
        } else {
            wx.showToast({
                icon: 'error',
                duration: 1200,
                title: '请添加菜品'
            });
        }

    }
});